//
//  KLMTool.swift
//  KLM
//
//  Created by 朱雨 on 2022/4/22.
//

import Foundation
import KeychainAccess
import SwiftUI
import HandyJSON
import nRFMeshProvision

class KLMTool {
        
    //获取设备的UUID，卸载APP会变化，适合现在使用。
    static func getAppUUID() -> String {
        if let uuid: String = KLMGetUserDefault("klmuuidString") as? String{
            return uuid
        }
        let uuid = UUID().uuidString
        KLMSetUserDefault("klmuuidString", uuid)
        return uuid
    }
}

extension KLMTool {
    
    /// 判断字符串是否是空的，去掉前后空格
    /// - Parameter string: string
    /// - Returns: 去掉前后空格的字符串
    static func isEmptyString(string: String?) -> String? {
        guard let string = string else { return nil }
        //字符串前后空格去掉
        let tt = string.trimmingCharacters(in: .whitespaces)
        if tt.isEmpty {
            return nil
        }
        return tt
    }
    ///根据code获取国家名称
    static func getCountryNameByPhoneCode(phoneCode: String) -> String? {
        var name: String?
        let sortedName = Bundle.isChineseLanguage() ? "sortedNameCH" : "sortedNameEN"
        let path = Bundle.main.path(forResource: sortedName, ofType: "plist")
        let sortedNameDict = NSDictionary(contentsOfFile: path ?? "") as! [String: Any]
        for values in sortedNameDict.values {
            let nameLists: [String] = values as! [String]
            for string in nameLists {
                let array = string.components(separatedBy: "+")
                let countryName = array.first?.trimmingCharacters(in: CharacterSet.whitespaces)
                let code = array.last
                if code == phoneCode {
                    name = countryName
                    break
                }
            }
            if name != nil {
                break
            }
        }
        return name
    }
}

extension KLMTool {
    
    //单独的字典（json）转模型
    static public func jsonToModel<T>(type:T.Type, json:Any) -> T? where T:Codable {
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []) else {
            return nil
        }
        guard let model = try? JSONDecoder.init().decode(type, from: jsonData) else {
            return nil
        }
        return model
    }
    
    //json数组转模型数组
    static public func jsonToModel<T>(type:T.Type, array:[[String:Any]]) -> [T]? where T:Codable {
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: array, options: []) else {
            return nil
        }
        guard let result = try? JSONDecoder.init().decode([T].self, from: jsonData) else {
            return nil
        }
        return result
    }
}

extension KLMTool {
    
    static public func checkBluetoothVersion(newestVersion: String, bleversion: String, EnMessage: String, CNMessage: String, viewController: UIViewController, comfirm: @escaping () -> (), cancel: @escaping () -> (), noNeedUpdate: @escaping () -> ()) {
                
        //最新版本 -- 服务器查询
        let value = bleversion.compare(newestVersion)
        if value == .orderedAscending {//左操作数小于右操作数，需要升级
            
            ///更新消息
            var updateMsg: String = EnMessage
            if Bundle.isChineseLanguage() {///使用中文
                updateMsg =  CNMessage
            }
            
            ///弹出更新框
            let vc = KLMLeftAlertViewController.init(title: KLMLocalizable.LANGLOC("Software update"), message: "V \(newestVersion)\n\(updateMsg)", preferredStyle: .alert)
            vc.addAction(UIAlertAction.init(title: KLMLocalizable.LANGLOC("Update"), style: .default, handler: { action in
                
                comfirm()
                
            }))
            vc.addAction(UIAlertAction.init(title: KLMLocalizable.LANGLOC("Cancel"), style: .cancel, handler: { action in
                
                cancel()
            }))
            
            viewController.present(vc, animated: true)
        } else {
            
            noNeedUpdate()
        }
    }
}

extension KLMTool {
    
    ///JSON字符串转模型，使用该方法，假如字符串没有某个key,但是模型有，这个时候模型中的key值不会Nil，保留默认值。
    static func jsonToModel(_ jsonStr:String?,_ modelType:HandyJSON.Type) ->BaseModel? {
        
        guard let jsonStr = isEmptyString(string: jsonStr) else {
            KLMLog("jsonoModel:字符串为空")
            return nil
        }

        return modelType.deserialize(from: jsonStr) as? BaseModel
        
    }
}

class BaseModel: HandyJSON {
    required init() {}
    func mapping(mapper: HelpingMapper) {   //自定义解析规则，日期数字颜色，如果要指定解析格式，子类实现重写此方法即可
        
    }
}

extension KLMTool {
    
    /// 添加设备的时候获取设备的名称：name - 1 格式
    /// - Parameter name: 设备名
    /// - Returns: name
    static func getDeviceName(name: String?) -> String? {
        var returnName: String?
        if let network = MeshNetworkManager.instance.meshNetwork, let name = name {
            var index = 1
            let notConfiguredNodes = network.nodes.filter({ !$0.isConfigComplete && !$0.isProvisioner})
            while true {
                let newName = name + "-" + "\(index)"
                if notConfiguredNodes.contains(where: {$0.name == newName}) {
                    index += 1
                } else {
                    returnName = newName
                    break
                }
            }
            
        }
        return returnName
    }
}

